package com.ocom.human.controller;


import com.alibaba.fastjson.JSON;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.ocom.common.constant.HumanServiceUrl;
import com.ocom.common.constant.MapKey;
import com.ocom.common.constant.WxServiceUrl;
import com.ocom.common.entity.human.EntityPersonTag;
import com.ocom.common.entity.human.EntityPersonTagRelation;
import com.ocom.common.entity.human.EntityPersonnelInfo;
import com.ocom.common.enums.ResultEnum;
import com.ocom.common.request.human.*;
import com.ocom.common.request.wx.UserAccessPageSetAccessRequest;
import com.ocom.common.resp.Result;
import com.ocom.common.utils.*;
import com.ocom.common.vo.PersonVo;
import com.ocom.common.vo.human.*;
import com.ocom.common.vo.webapi.ExcelAddPersonVo;
import com.ocom.common.vo.webapi.UpdateAccessVo;
import com.ocom.human.feignclient.MqSimple;
import com.ocom.human.feignclient.WebApiClient;
import com.ocom.human.service.MjKaoqinService;
import com.ocom.human.service.PersonTagRelationService;
import com.ocom.human.service.PersonnelFeatureService;
import com.ocom.human.service.PersonnelInfoService;
import com.ocom.redis.util.RedisUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.OptionalLong;
import java.util.stream.Collectors;


@RestController
public class PersonInfoController {
    private final Logger log = LoggerFactory.getLogger(PersonInfoController.class);
    @Autowired
    private PersonnelInfoService personnelInfoService;

    @Autowired
    private PersonnelFeatureService personnelFeatureService;

    @Autowired
    private PersonTagRelationService personTagRelationService;

    @Autowired
    private WebApiClient webApiClient;

    @Autowired
    private PersonTagController personTagController;

    @Autowired
    private MjKaoqinService mjKaoqinService;

    @Autowired
    private MqSimple mqSimple;


    @Resource
    private RedisUtil redisUtil;

    /**
     * 获取人员列表personnel/getPersonInfo
     */
    @PostMapping(HumanServiceUrl.URL_PersonnelGetPersonInfo)
    public Result PersonnelGetPersonInfo(@Validated @RequestBody UserInfoVo userInfoVo) {
        if (!userInfoVo.getOnlyOne()) {
            PageHelper.startPage(userInfoVo.getPage(), userInfoVo.getSize());
            List<UserInfoYkmVo> userInfoYkmVos = personnelInfoService.PersonnelGetPersonInfo(userInfoVo, userInfoVo.getComId());
            log.info("List<UserInfoYkmVo>:{{}}", userInfoYkmVos);
            PageInfo<UserInfoYkmVo> userInfoYkmVoPageInfo = new PageInfo<>(userInfoYkmVos);
            Map<String, Object> map = new HashMap<>();
            map.put("total", userInfoYkmVoPageInfo.getTotal());
            map.put("list", userInfoYkmVos);
            log.info("获取人员列表:{{}}", map);
            return ResultUtil.success(map);
        } else {


            EntityPersonnelInfo entityPersonnelInfo = personnelInfoService.getPersonInfo(userInfoVo.getComId(), userInfoVo);
            if (entityPersonnelInfo == null) {
                return ResultUtil.error(ResultEnum.Err_2036);
            }
            List<EntityPersonTagRelation> list = personTagRelationService.getByComPId(userInfoVo.getComId(),userInfoVo.getPId());
            if(list!=null && list.size()>0){
                List<Integer> tagIds = list.stream().map(EntityPersonTagRelation -> EntityPersonTagRelation.getTagId()).collect(Collectors.toList());
                entityPersonnelInfo.setPTags(StringUtils.join(tagIds,","));
            }
            return ResultUtil.success(entityPersonnelInfo);
        }
    }

    @PostMapping(HumanServiceUrl.URL_PersonnelGetPersonInfoByStatus)
    public Result PersonnelGetPersonInfoByStatus(@Validated @RequestBody UserInfoVo userInfoVo) {

        EntityPersonnelInfo entityPersonnelInfo = personnelInfoService.getPersonInfoByStatus(userInfoVo.getComId(), userInfoVo);
        if (entityPersonnelInfo == null) {
            return ResultUtil.error(ResultEnum.Err_2036);
        }
        return ResultUtil.success(entityPersonnelInfo);

    }

    @PostMapping(HumanServiceUrl.URL_PersonnelGetPersonInfoById)
    public Result PersonnelGetPersonInfoById(@Validated @RequestBody UserInfoVo userInfoVo) {

        List<EntityPersonnelInfo> personInfoGtPId = personnelInfoService.getPersonInfoGtPId(userInfoVo.getComId(), userInfoVo);

        OptionalLong max = personInfoGtPId.stream().mapToLong(EntityPersonnelInfo::getPId).max();

        Map<String, Object> map = new HashMap<>();
        map.put("newPid", max.getAsLong());
        map.put("personList", personInfoGtPId);
        return ResultUtil.success(map);

    }

    /**
     * 获取人员信息 getPersonInfo
     */
    @GetMapping(HumanServiceUrl.URL_GetPersonInfoTest)
    public Result GetPersonInfoTest(Long comId, Long pId) {
        return ResultUtil.success(personnelInfoService.getPersonInfoOne(comId, pId));
    }

    /**
     * 获取人员信息 getPersonInfo
     */
    @GetMapping(HumanServiceUrl.URL_GetPersonInfo)
    public Result<UserInfoYkmVo> GetPersonInfo(Long comId, Long pId) {

        UserInfoYkmVo personInfoById = personnelInfoService.getPersonInfoById(comId, pId);
        if (personInfoById == null) {
            log.info("获取人员信息为空");
            return ResultUtil.error(ResultEnum.Err_1000, "获取人员信息为空");
        }
//        log.info("personInfoById:{{}}", personInfoById);
//        String key = MD5.MD5Encode(comId.toString(), "utf8");
//
//        String decryptIdentity = AES.decrypt(personInfoById.getEncryIdentity(), key);
//        if (decryptIdentity != null && !decryptIdentity.isEmpty()) {
//            personInfoById.setPIdentity(decryptIdentity);
//        }
//        String decryptPhone = AES.decrypt(personInfoById.getEncryPhone(), key);
//        if (decryptPhone != null && !decryptPhone.isEmpty()) {
//            personInfoById.setPPhone(decryptPhone);
//        }
        return ResultUtil.success(personInfoById);
    }


    // 获取人员信息的未脱敏的信息(getPersonnelNoDesensitized)
    @GetMapping(HumanServiceUrl.URL_GetPersonnelNoDesensitized)
    public Result GetPersonnelNoDesensitized(Long comId, Long pId) {
        EntityPersonnelInfo personnelInfo = personnelInfoService.GetPersonnelNoDesensitized(comId, pId);
        if (personnelInfo == null) {
            log.info("获取人员信息为空");
            return ResultUtil.error(ResultEnum.Err_1000, "获取人员信息为空");
        }
        log.info("personInfoById:{{}}", personnelInfo);
        String key = MD5.MD5Encode(comId.toString(), "utf8");
        String decryptIdentity = AES.decrypt(personnelInfo.getEncryIdentity(), key);
        if (decryptIdentity != null && !decryptIdentity.isEmpty()) {
            personnelInfo.setPIdentity(decryptIdentity);
        }
        String decryptPhone = AES.decrypt(personnelInfo.getEncryPhone(), key);
        if (decryptPhone != null && !decryptPhone.isEmpty()) {
            personnelInfo.setPPhone(decryptPhone);
        }

        return ResultUtil.success(personnelInfo);
    }

    /**
     * 人事 2.2.7 匹配人员 personnel/regexp
     */
    @PostMapping(HumanServiceUrl.URL_PersonnelRegexp)
    public Result regexpPerson(Long companyId, String name, String phone, String pIdentity) {

        return ResultUtil.success(personnelInfoService.regexpPerson(companyId, name, phone, pIdentity));
    }


    /**
     * 新增人员信息
     */
    @PostMapping(HumanServiceUrl.URL_PersonnelAddPerson)
    public Result AddPerson(@Validated @RequestBody PersonVo personVo) {
//        String key = MD5.MD5Encode(personVo.getComId().toString(), "utf8");
//        personVo.setEncryIdentity(AES.encrypt(personVo.getPIdentity(), key));
//        if (personVo.getPPhone() != null && !personVo.getPPhone().isEmpty()) {
//            personVo.setEncryPhone(AES.encrypt(personVo.getPPhone(), key));
//        }
        if (!CommonUtil.isNull(personVo.getPPhone())) {
            personVo.setEncryPhone(CommonUtil.encryptPhone(personVo.getPPhone()));
        }
        if (!CommonUtil.isNull(personVo.getPIdentity())) {
            personVo.setEncryIdentity(CommonUtil.encryptIdCard(personVo.getPIdentity()));
        }
        assert personVo.getPCode() != null;
        boolean bo = redisUtil.lock("addPerson:comId:"+personVo.getComId()+"pCode:"+personVo.getPCode(),10);
        if(!bo){
            log.error("人员编号已存在:{{}}", personVo.getPCode());
            return ResultUtil.error(ResultEnum.Err_4103);
        }
        if (!CommonUtil.isNull(personVo.getPIdentity())) {
            bo = redisUtil.lock("addPerson:comId:" + personVo.getComId() + "pIdentity:" + personVo.getPIdentity(), 10);
            if (!bo) {
                log.error("人员身份证已存在:{{}}", personVo);
                return ResultUtil.error(ResultEnum.Err_4103);
            }
        }
        EntityPersonnelInfo pCodeUnique = personnelInfoService.pCodeUnique(personVo.getComId(), personVo.getPCode());
        if (pCodeUnique != null) {
            log.error("人员编号重复:{{}}", personVo);
            return ResultUtil.error(ResultEnum.Err_3025, "人员编号重复");
        }
//        assert personVo.getEncryIdentity() != null;
        EntityPersonnelInfo personnelInfo = null;
        if (!CommonUtil.isNull(personVo.getPIdentity())) {
            personnelInfo = personnelInfoService.getPersonInfopIdentity(personVo.getComId(), personVo.getPIdentity());
        }

        if (personnelInfo != null && !personnelInfo.getPId().equals(personVo.getPId())) {
            log.error("身份证号重复：{{}}", personnelInfo);
            return ResultUtil.error(ResultEnum.Err_3025);
        }
        EntityPersonnelInfo personInfopPhone = null;
        if (!CommonUtil.isNull(personVo.getPPhone())) {
            personInfopPhone = personnelInfoService.getPersonInfopPhone(personVo.getComId(), personVo.getPPhone());
        }
        log.info("personInfopPhone{{}}", personInfopPhone);
        if (personInfopPhone != null && !personInfopPhone.getPId().equals(personVo.getPId())) {
            log.error("手机号重复：{{}}", personInfopPhone);
            return ResultUtil.error(ResultEnum.Err_3015);
        }

        EntityPersonnelInfo entityPersonnelInfo = null;
        try {
            entityPersonnelInfo = personnelInfoService.AddPerson(personVo, personVo.getComId());

            feature(entityPersonnelInfo.getComId(), entityPersonnelInfo.getPId(), entityPersonnelInfo.getPPhotoUrl(), entityPersonnelInfo.getPPhotoUrl2());

        } catch (Exception exception) {
            log.error("新增人员信息失败：{{}}", exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_2009, "新增人员信息失败");
        }
        return ResultUtil.success(entityPersonnelInfo);
    }


    /**
     * 修改人员信息
     */
    @PostMapping(HumanServiceUrl.URL_PersonnelUpdatePerson)
    public Result UpdatePerson(@RequestBody PersonVo personVo) {

        if(CommonUtil.isNull(personVo.getPCode()) && personVo.getPId()==null){
            return ResultUtil.error(ResultEnum.Err_203);
        }

        log.info("修改人员信息请求参数:{{}}", personVo);
//        String key = MD5.MD5Encode(personVo.getComId().toString(), "utf8");

        log.info("personVo{{}}", personVo);
        if (personVo.getPCode() != null && !personVo.getPCode().isEmpty()) {
            EntityPersonnelInfo pCodeUnique = personnelInfoService.pCodeUnique(personVo.getComId(), personVo.getPCode());
            if (pCodeUnique != null && !pCodeUnique.getPId().equals(personVo.getPId())) {
                log.error("人员编号已存在:{{}}", personVo.getPCode());
                return ResultUtil.error(ResultEnum.Err_306);
            }
        }
//        if (!pCodeUnique.getPCode().isEmpty() && pCodeUnique.getPCode()!= null &&!pCodeUnique.getPId().equals(personVo.getPId()) )
//        {
//            log.error("人员编号已存在:{{}}",personVo.getPCode());
//            return ResultUtil.error(ResultEnum.Err_306,personVo.getPCode());
//        }
        if (StringUtils.isNotEmpty(personVo.getPIdentity())) {
            EntityPersonnelInfo personnelInfo = personnelInfoService.getPersonInfopIdentity(personVo.getComId(), personVo.getPIdentity());
            if (personnelInfo != null && !CommonUtil.isNull(personVo.getPIdentity()) && !personnelInfo.getPId().equals(personVo.getPId())) {
                log.error("身份证号重复：{{}}", personnelInfo);
                return ResultUtil.error(ResultEnum.Err_3025, "身份证号重复");
            }
        }
//        if(StringUtils.isNotEmpty(personVo.getPPhone())){
//            personVo.setEncryPhone(AES.encrypt(personVo.getPPhone(), key));
//            if (personVo.getEncryPhone()!=null && !personVo.getEncryPhone().isEmpty()){
//                EntityPersonnelInfo personInfopPhone = personnelInfoService.getPersonInfopPhone(personVo.getComId(), personVo.getEncryPhone());
//                log.info("personInfopPhone{{}}",personInfopPhone);
//                if (personInfopPhone!= null && !personInfopPhone.getPId().equals(personVo.getPId()) ){
//                    log.error("手机号重复：{{}}",personInfopPhone);
//                    return ResultUtil.error(ResultEnum.Err_3015,"手机号重复");
//                }
//            }
//        }
        EntityPersonnelInfo entityPersonnelInfo = null;

//        if (!CommonUtil.isNull(personVo.getPTags())) {
//            if (!personVo.getPTags().startsWith(",")) {
//                personVo.setPTags("," + personVo.getPTags());
//            }
//            if (!personVo.getPTags().endsWith(",")) {
//                personVo.setPTags(personVo.getPTags() + ",");
//            }
//        } else {
//            personVo.setPTags("");
//        }

        try {
            entityPersonnelInfo = personnelInfoService.UpdatePerson(personVo, personVo.getComId());

            feature(entityPersonnelInfo.getComId(), entityPersonnelInfo.getPId(), entityPersonnelInfo.getPPhotoUrl(), entityPersonnelInfo.getPPhotoUrl2());

        } catch (Exception exception) {
            log.error("修改人员信息失败：{{}}", exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_2009, "修改人员信息失败");
        }

        return ResultUtil.success(entityPersonnelInfo);
    }

    private void feature(Long comId, Long pId, String url, String url2) {
        try {
            if (StringUtils.isNotBlank(url) || StringUtils.isNotBlank(url2)) {
                FeatureRequest featureRequest = new FeatureRequest();
                featureRequest.setComId(comId);
                featureRequest.setPId(pId);
                featureRequest.setUrl(url);
                featureRequest.setUrl2(url2);
                personnelFeatureService.feature(comId, featureRequest);
            }

        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 修改人员信息
     */
    @PostMapping(HumanServiceUrl.URL_PersonnelUpdatePersonNotCheckPhone)
    public Result UpdatePersonNotCheckPhone(@RequestBody PersonVo personVo) {

        log.info("修改人员信息请求参数:{{}}", personVo);
        String key = MD5.MD5Encode(personVo.getComId().toString(), "utf8");

        log.info("personVo{{}}", personVo);
        if (personVo.getPCode() != null && !personVo.getPCode().isEmpty()) {
            EntityPersonnelInfo pCodeUnique = personnelInfoService.pCodeUnique(personVo.getComId(), personVo.getPCode());
            if (pCodeUnique != null && !pCodeUnique.getPId().equals(personVo.getPId())) {
                log.error("人员编号已存在:{{}}", personVo.getPCode());
                return ResultUtil.error(ResultEnum.Err_306, personVo.getPCode());
            }
        }
//        if (!pCodeUnique.getPCode().isEmpty() && pCodeUnique.getPCode()!= null &&!pCodeUnique.getPId().equals(personVo.getPId()) )
//        {
//            log.error("人员编号已存在:{{}}",personVo.getPCode());
//            return ResultUtil.error(ResultEnum.Err_306,personVo.getPCode());
//        }
        if (StringUtils.isNotEmpty(personVo.getPIdentity())) {
            personVo.setEncryIdentity(AES.encrypt(personVo.getPIdentity(), key));
            EntityPersonnelInfo personnelInfo = personnelInfoService.getPersonInfopIdentity(personVo.getComId(), personVo.getEncryIdentity());
            if (personnelInfo != null && !CommonUtil.isNull(personVo.getEncryIdentity()) && !personnelInfo.getPId().equals(personVo.getPId())) {
                log.error("身份证号重复：{{}}", personnelInfo);
                return ResultUtil.error(ResultEnum.Err_3025, "身份证号重复");
            }
        }

//        if(StringUtils.isNotEmpty(personVo.getPPhone())){
//            personVo.setEncryPhone(AES.encrypt(personVo.getPPhone(), key));
//            if (personVo.getEncryPhone()!=null && !personVo.getEncryPhone().isEmpty()){
//                EntityPersonnelInfo personInfopPhone = personnelInfoService.getPersonInfopPhone(personVo.getComId(), personVo.getEncryPhone());
//                log.info("personInfopPhone{{}}",personInfopPhone);
//                if (personInfopPhone!= null && !personInfopPhone.getPId().equals(personVo.getPId()) ){
//                    log.error("手机号重复：{{}}",personInfopPhone);
//                    return ResultUtil.error(ResultEnum.Err_3015,"手机号重复");
//                }
//            }
//        }
        EntityPersonnelInfo entityPersonnelInfo = null;

//        if (!CommonUtil.isNull(personVo.getPTags())) {
//            if (!personVo.getPTags().startsWith(",")) {
//                personVo.setPTags("," + personVo.getPTags());
//            }
//            if (!personVo.getPTags().endsWith(",")) {
//                personVo.setPTags(personVo.getPTags() + ",");
//            }
//        } else {
//            personVo.setPTags("");
//        }

        try {
            entityPersonnelInfo = personnelInfoService.UpdatePerson(personVo, personVo.getComId());

        } catch (Exception exception) {
            log.error("修改人员信息失败：{{}}", exception.getMessage());
            return ResultUtil.error(ResultEnum.Err_2009, "修改人员信息失败");
        }

        return ResultUtil.success(entityPersonnelInfo);
    }

    /**
     * 导入人员信息（importUserInfo）
     */
    @PostMapping(HumanServiceUrl.URL_ImportUserInfo)
    public Result ImportUserInfo(@RequestBody ExcelAddPersonVo excelAddPersonVo) {
        Long comId = excelAddPersonVo.getComId();
        String areaGroop = excelAddPersonVo.getAreaGroop();
        Long accTypeId = excelAddPersonVo.getAccTypeId();
        Long timestamp = excelAddPersonVo.getTimestamp();
        List<EntityPersonnelInfo> personnelInfos = excelAddPersonVo.getPersonnelInfos();

        log.info("导入人员信息,请求参数【{}】", excelAddPersonVo);


//        String key = MD5.MD5Encode(comId.toString(), "utf8");
        UserAccessPageSetAccessRequest request = new UserAccessPageSetAccessRequest();
        try {
            UpdateAccessVo updateAccessVo = new UpdateAccessVo();
            updateAccessVo.setComId(comId);

            if (timestamp == 0l) {
                timestamp = System.currentTimeMillis();
                Map<String, Object> map1 = new HashMap<>();
                map1.put("key", "ImportErr:detail:" + comId + ":" + timestamp);
                map1.put("type", 2);
                map1.put("name", "人员批量导入");
                map1.put("timestamp", timestamp);
                map1.put("datetime", DateUtil.getDateTime());
                redisUtil.leftPush("ImportErr:" + comId, map1, 86400l);
            }


            for (EntityPersonnelInfo entityPersonnelInfo : personnelInfos) {
                if (null != entityPersonnelInfo.getAccTypeId()) {
                    accTypeId = entityPersonnelInfo.getAccTypeId().longValue();
                }

                String errMsg = "";

                log.info("entityPersonnelInfo{{}}", entityPersonnelInfo);
                if (entityPersonnelInfo.getPIdentity() != null && !entityPersonnelInfo.getPIdentity().isEmpty()) {
                    entityPersonnelInfo.setEncryIdentity(CommonUtil.encryptIdCard(entityPersonnelInfo.getPIdentity()));
             //       entityPersonnelInfo.setEncryIdentity(AES.encrypt(entityPersonnelInfo.getPIdentity(), key));
                }
                if (entityPersonnelInfo.getPPhone() != null && !entityPersonnelInfo.getPPhone().isEmpty()) {
//                    entityPersonnelInfo.setEncryPhone(AES.encrypt(entityPersonnelInfo.getPPhone(), key));
                    entityPersonnelInfo.setEncryPhone(CommonUtil.encryptPhone(entityPersonnelInfo.getPPhone()));
                }
                if (entityPersonnelInfo.getPCode() != null && !CommonUtil.isNull(entityPersonnelInfo.getPCode())) {
                    EntityPersonnelInfo pCodeUnique = personnelInfoService.pCodeUnique(entityPersonnelInfo.getComId(), entityPersonnelInfo.getPCode());
                    if (pCodeUnique != null) {

                        if(excelAddPersonVo.getImportType() == 1){
                            log.info("pCodeUnique{{}}", pCodeUnique);
                            log.info("人员编号已存在,不执行操作:{{}}", pCodeUnique);
                            entityPersonnelInfo.setPId(pCodeUnique.getPId());

                            errMsg = "人员编号已存在,不执行操作";
                            Map<String, Object> map3 = new HashMap<>();
                            map3.put("errMsg", errMsg);
                            map3.put("pCode",pCodeUnique.getPCode());
                            map3.put("pName",pCodeUnique.getPName());
                            map3.put("nCode",entityPersonnelInfo.getPCode());
                            map3.put("nName",entityPersonnelInfo.getPName());
                            map3.put("json", entityPersonnelInfo);
                            redisUtil.leftPush("ImportErr:detail:" + comId + ":" + timestamp, map3, 86400l);

                        }else if(excelAddPersonVo.getImportType() == 2){
                            log.info("pCodeUnique{{}}", pCodeUnique);
                            log.info("人员编号已存在,执行更新操作:{{}}", pCodeUnique);
                            entityPersonnelInfo.setPId(pCodeUnique.getPId());
                            personnelInfoService.updateUser(pCodeUnique.getComId(), entityPersonnelInfo);


                            errMsg = "人员编号已存在,执行更新操作";
                            Map<String, Object> map3 = new HashMap<>();
                            map3.put("errMsg", errMsg);
                            map3.put("pCode",pCodeUnique.getPCode());
                            map3.put("pName",pCodeUnique.getPName());
                            map3.put("nCode",entityPersonnelInfo.getPCode());
                            map3.put("nName",entityPersonnelInfo.getPName());
                            map3.put("json", entityPersonnelInfo);
                            redisUtil.leftPush("ImportErr:detail:" + comId + ":" + timestamp, map3, 86400l);
                        }



                        if (areaGroop != null && !areaGroop.isEmpty()) {
                            try {
                                List<AreaGroopVo> areaGroopVos = JSON.parseArray(areaGroop, AreaGroopVo.class);
                                request.setCompanyId(comId);
                                request.setUserId(pCodeUnique.getPId());
                                request.setPId(pCodeUnique.getPId());
                                request.setRegionId(0L);
                                for (AreaGroopVo areaGroopVo : areaGroopVos) {
                                    request.setAreaNo(areaGroopVo.getAreaId());
                                    if (areaGroopVo.getRoleId() == null) {
                                        areaGroopVo.setRoleId(0l);
                                    }
                                    request.setRoleI(areaGroopVo.getRoleId());
                                    log.info("-------------------------------------");
                                    log.info("MQ设置区域发送参数：{{}}", request);
                                    mqSimple.ChangeAccess(request);
                                }

                            } catch (Exception exception) {
                                log.error("设置区域权限-getMessage{{}}", exception);
                            }

                        }
                        if (accTypeId != null && accTypeId > 0) {
                            try {
                                Map<String, Object> map = new HashMap<>();
                                MapKey mapKey = new MapKey();
                                map.put(mapKey.getKey_pId(), entityPersonnelInfo.getPId());
                                map.put(mapKey.getKey_comId(), entityPersonnelInfo.getComId());
                                map.put(mapKey.getKey_accountNo(), entityPersonnelInfo.getComId() + "P" + entityPersonnelInfo.getPId());
                                map.put(mapKey.getKey_accountName(), entityPersonnelInfo.getComId() + "P" + entityPersonnelInfo.getPId());
                                map.put(mapKey.getKey_accountId(), accTypeId);
                                map.put(mapKey.getKey_accountState(), 0);
                                map.put(mapKey.getKey_endDate(),DateUtil.getStrDate2(entityPersonnelInfo.getAccountEndDate(),"yyyy-MM-dd"));
                                log.info("-------------------------------------");
                                log.info("MQ设置区域发送参数：{{}}", map);
                                mqSimple.AddXFAccount(map);

                            } catch (Exception exception) {
                                log.error("消费账户-getMessage{{}}", exception);
                            }
                        }
//                        try{
//                            updateAccessVo.setType(1);
//                            updateAccessVo.setPCode(entityPersonnelInfo.getPCode());
//                            webApiClient.updateUserAccess(updateAccessVo);
//                        }catch (Exception e){
//                            log.info("人员更新權限異常:{{}}",e);
//                        }
                        managePerTagRelation(comId, pCodeUnique.getPId(), entityPersonnelInfo.getPerTags());

                        continue;
                    }
                }

                if (!CommonUtil.isNull(entityPersonnelInfo.getPIdentity())) {
                    EntityPersonnelInfo personnelInfo = personnelInfoService.getPersonInfopIdentity(entityPersonnelInfo.getComId(), entityPersonnelInfo.getPIdentity());
                    if (personnelInfo != null) {
                        if(excelAddPersonVo.getImportType() == 1){
                            log.info("personnelInfo{{}}", personnelInfo);
                            log.info("身份证号重复,不执行操作：{{}}", personnelInfo);
                            entityPersonnelInfo.setPId(personnelInfo.getPId());

                            errMsg = "身份证号重复,不执行操作";
                            Map<String, Object> map3 = new HashMap<>();
                            map3.put("errMsg", errMsg);
                            map3.put("pCode",personnelInfo.getPCode());
                            map3.put("pName",personnelInfo.getPName());
                            map3.put("nCode",entityPersonnelInfo.getPCode());
                            map3.put("nName",entityPersonnelInfo.getPName());
                            map3.put("json", entityPersonnelInfo);
                            redisUtil.leftPush("ImportErr:detail:" + comId + ":" + timestamp, map3, 86400l);

                        }else if(excelAddPersonVo.getImportType() == 2){
                            log.info("personnelInfo{{}}", personnelInfo);
                            log.info("身份证号重复,执行更新操作：{{}}", personnelInfo);
                            entityPersonnelInfo.setPId(personnelInfo.getPId());
                            personnelInfoService.updateUser(personnelInfo.getComId(), entityPersonnelInfo);

                            errMsg = "身份证号重复,执行更新操作";
                            Map<String, Object> map3 = new HashMap<>();
                            map3.put("errMsg", errMsg);
                            map3.put("pCode",personnelInfo.getPCode());
                            map3.put("pName",personnelInfo.getPName());
                            map3.put("nCode",entityPersonnelInfo.getPCode());
                            map3.put("nName",entityPersonnelInfo.getPName());
                            map3.put("json", entityPersonnelInfo);
                            redisUtil.leftPush("ImportErr:detail:" + comId + ":" + timestamp, map3, 86400l);
                        }



                        if (areaGroop != null && !areaGroop.isEmpty()) {
                            try {
                                List<AreaGroopVo> areaGroopVos = JSON.parseArray(areaGroop, AreaGroopVo.class);
                                request.setCompanyId(comId);
                                request.setUserId(personnelInfo.getPId());
                                request.setPId(personnelInfo.getPId());
                                request.setRegionId(0L);
                                for (AreaGroopVo areaGroopVo : areaGroopVos) {
                                    request.setAreaNo(areaGroopVo.getAreaId());
                                    if (areaGroopVo.getRoleId() == null) {
                                        areaGroopVo.setRoleId(0l);
                                    }
                                    request.setRoleI(areaGroopVo.getRoleId());
                                    log.info("-------------------------------------");
                                    log.info("MQ设置区域发送参数：{{}}", request);
                                    mqSimple.ChangeAccess(request);
                                }

                            } catch (Exception exception) {
                                log.error("MQ设置区域发送参数-getMessage{{}}", exception);
                            }
                        }
                        if (accTypeId != null && accTypeId > 0) {
                            try {
                                Map<String, Object> map = new HashMap<>();
                                MapKey mapKey = new MapKey();
                                map.put(mapKey.getKey_pId(), entityPersonnelInfo.getPId());
                                map.put(mapKey.getKey_comId(), entityPersonnelInfo.getComId());
                                map.put(mapKey.getKey_accountNo(), entityPersonnelInfo.getComId() + "P" + entityPersonnelInfo.getPId());
                                map.put(mapKey.getKey_accountName(), entityPersonnelInfo.getComId() + "P" + entityPersonnelInfo.getPId());
                                map.put(mapKey.getKey_accountId(), accTypeId);
                                map.put(mapKey.getKey_accountState(), 0);
                                map.put(mapKey.getKey_endDate(),DateUtil.getStrDate2(entityPersonnelInfo.getAccountEndDate(),"yyyy-MM-dd"));
                                log.info("-------------------------------------");
                                log.info("MQ添加消费账户：{{}}", map);
                                mqSimple.AddXFAccount(map);


                            } catch (Exception exception) {
                                log.error("MQ添加消费账户-getMessage{{}}", exception);
                            }

                        }
//                        try{
//                            updateAccessVo.setType(1);
//                            updateAccessVo.setPCode(entityPersonnelInfo.getEncryIdentity());
//                            webApiClient.updateUserAccess(updateAccessVo);
//                        }catch (Exception e){
//                            log.info("人员更新權限異常:{{}}",e);
//                        }
                        managePerTagRelation(comId, personnelInfo.getPId(), entityPersonnelInfo.getPerTags());

                        continue;
                    }
                }
                /**
                if (entityPersonnelInfo.getEncryPhone() != null && !CommonUtil.isNull(entityPersonnelInfo.getEncryPhone())) {
                    EntityPersonnelInfo personInfopPhone = personnelInfoService.getPersonInfopPhone(entityPersonnelInfo.getComId(), entityPersonnelInfo.getEncryPhone());
                    if (personInfopPhone != null) {
                        log.info("personInfopPhone{{}}", personInfopPhone);
                        log.info("手机号重复,执行更新操作：{{}}", personInfopPhone);
                        entityPersonnelInfo.setPId(personInfopPhone.getPId());
                        personnelInfoService.updateUser(personInfopPhone.getComId(), entityPersonnelInfo);

                        errMsg = "手机号重复,执行更新操作";
                        Map<String, Object> map3 = new HashMap<>();
                        map3.put("errMsg", errMsg);
                        map3.put("json", entityPersonnelInfo);
                        redisUtil.leftPush("ImportErr:detail:" + comId + ":" + timestamp, map3, 86400l);


                        if (areaGroop != null && !areaGroop.isEmpty()) {
                            try {
                                List<AreaGroopVo> areaGroopVos = JSON.parseArray(areaGroop, AreaGroopVo.class);
                                request.setCompanyId(comId);
                                request.setUserId(personInfopPhone.getPId());
                                request.setPId(personInfopPhone.getPId());
                                request.setRegionId(0L);
                                for (AreaGroopVo areaGroopVo : areaGroopVos) {
                                    request.setAreaNo(areaGroopVo.getAreaId());
                                    if (areaGroopVo.getRoleId() == null) {
                                        areaGroopVo.setRoleId(0l);
                                    }
                                    request.setRoleI(areaGroopVo.getRoleId());
                                    log.info("-------------------------------------");
                                    log.info("MQ设置区域发送参数：{{}}", request);
                                    mqSimple.ChangeAccess(request);
                                }

                            } catch (Exception exception) {
                                log.error("getMessage{{}}", exception);
                            }
                        }
                        if (accTypeId != null && accTypeId > 0) {
                            try {
                                Map<String, Object> map = new HashMap<>();
                                MapKey mapKey = new MapKey();
                                map.put(mapKey.getKey_pId(), entityPersonnelInfo.getPId());
                                map.put(mapKey.getKey_comId(), entityPersonnelInfo.getComId());
                                map.put(mapKey.getKey_accountNo(), entityPersonnelInfo.getComId() + "P" + entityPersonnelInfo.getPId());
                                map.put(mapKey.getKey_accountName(), entityPersonnelInfo.getComId() + "P" + entityPersonnelInfo.getPId());
                                map.put(mapKey.getKey_accountId(), accTypeId);
                                map.put(mapKey.getKey_accountState(), 0);
                                map.put(mapKey.getKey_endDate(),DateUtil.getStrDate2(entityPersonnelInfo.getAccountEndDate(),"yyyy-MM-dd"));
                                log.info("-------------------------------------");
                                log.info("MQ设置区域发送参数：{{}}", map);
                                mqSimple.AddXFAccount(map);
                            } catch (Exception exception) {
                                log.error("getMessage{{}}", exception);
                            }

                        }
//                        try{
//                            updateAccessVo.setType(4);
//                            updateAccessVo.setPhone(entityPersonnelInfo.getEncryPhone());
//                            webApiClient.updateUserAccess(updateAccessVo);
//                        }catch (Exception e){
//                            log.info("人员更新權限異常:{{}}",e);
//                        }
                        managePerTagRelation(comId, personInfopPhone.getPId(), entityPersonnelInfo.getPerTags());

                        continue;
                    }
                }

                **/

                log.info("插入人员数据开始{{}}", entityPersonnelInfo);
                try {
                    if(CommonUtil.isNull(entityPersonnelInfo.getPPwd())){
                        entityPersonnelInfo.setPPwd("000000");
                    }
                    EntityPersonnelInfo personnelInfo = personnelInfoService.ImportUserInfo(comId, entityPersonnelInfo);
                    log.info("personnelInfo{{}}", personnelInfo);
                    if (areaGroop != null && !areaGroop.isEmpty()) {
                        List<AreaGroopVo> areaGroopVos = JSON.parseArray(areaGroop, AreaGroopVo.class);
                        request.setCompanyId(comId);
                        request.setUserId(personnelInfo.getPId());
                        request.setPId(personnelInfo.getPId());
                        request.setRegionId(0L);
                        for (AreaGroopVo areaGroopVo : areaGroopVos) {
                            request.setAreaNo(areaGroopVo.getAreaId());
                            if (areaGroopVo.getRoleId() == null) {
                                areaGroopVo.setRoleId(0l);
                            }
                            request.setRoleI(areaGroopVo.getRoleId());
                            log.info("-------------------------------------");
                            log.info("MQ设置区域发送参数：{{}}", request);
                            mqSimple.ChangeAccess(request);
                        }
                    }
                    if (accTypeId != null && accTypeId > 0) {
                        try {
                            Map<String, Object> map = new HashMap<>();
                            MapKey mapKey = new MapKey();
                            map.put(mapKey.getKey_pId(), personnelInfo.getPId());
                            map.put(mapKey.getKey_comId(), entityPersonnelInfo.getComId());
                            map.put(mapKey.getKey_accountNo(), entityPersonnelInfo.getComId() + "P" + entityPersonnelInfo.getPId());
                            map.put(mapKey.getKey_accountName(), entityPersonnelInfo.getComId() + "P" + entityPersonnelInfo.getPId());
                            map.put(mapKey.getKey_accountId(), accTypeId);
                            map.put(mapKey.getKey_accountState(), 0);
                            map.put("accTypeId", accTypeId);
                            map.put(mapKey.getKey_endDate(),DateUtil.getStrDate2(entityPersonnelInfo.getAccountEndDate(),"yyyy-MM-dd"));
                            log.info("-------------------------------------");
                            log.info("MQ 添加消费用户：{{}}", map);
                            mqSimple.AddXFAccount(map);


                        } catch (Exception exception) {
                            log.error("getMessage{{}}", exception.getMessage());
                        }
                    }

                    managePerTagRelation(comId, personnelInfo.getPId(), entityPersonnelInfo.getPerTags());

                } catch (Exception exception) {
                    log.error("人员插入失败 - getMessage{{}}", exception);
                    errMsg = "人员插入失败";
                    Map<String, Object> map3 = new HashMap<>();
                    map3.put("errMsg", errMsg);
                    map3.put("pCode","");
                    map3.put("pName","");
                    map3.put("nCode",entityPersonnelInfo.getPCode());
                    map3.put("nName",entityPersonnelInfo.getPName());
                    map3.put("json", entityPersonnelInfo);
                    redisUtil.leftPush("ImportErr:detail:" + comId + ":" + timestamp, map3, 86400l);
                }
            }

        } catch (Exception exception) {
            exception.printStackTrace();
            log.error("exception{{}}", exception.getMessage());
        }
        return ResultUtil.success();
    }

    private void managePerTagRelation(Long comId, Long pId, List<EntityPersonTag> perTags){
        if (null != perTags && 0 < perTags.size()) {
            ManagePerTagRelationRequest managePerTagRelationRequest = new ManagePerTagRelationRequest();
            managePerTagRelationRequest.setComId(comId);
            managePerTagRelationRequest.setType(1);
            ManagePerTagRelationRequest.PerList perList = managePerTagRelationRequest.getPerList();
            List<ManagePerTagRelationRequest.PerTag> perTagsList = perList.getPerTags();

            for (EntityPersonTag tag : perTags) {
                ManagePerTagRelationRequest.PerTag perTag = new ManagePerTagRelationRequest.PerTag();
                perTag.setTagId(tag.getTagId());
                perTagsList.add(perTag);
            }

            perList.setPerTags(perTagsList);
            perList.setPId(pId);

            List<ManagePerTagRelationRequest.PerList> perLists = managePerTagRelationRequest.getPerLists();
            perLists.add(perList);

            Result result = personTagController.managePerTagRelation(managePerTagRelationRequest);
            if (200 != result.getCode()) {
                log.error("人员标签插入失败 - getMessage{{}}", result.getCode() + "|" + result.getData());
            }
        }

    }

    // 人员列表查询（getPersonnelList）
    @PostMapping(HumanServiceUrl.URL_GetPersonnelList)
    public Result<PageInfo<UserListRVo>> GetPersonnelList(@Validated @RequestBody UserListVo userListVo) {

        List<UserListRVo> userListRVos = personnelInfoService.GetPersonnelList(userListVo.getComId(), userListVo);
        try {
            List<Long> pIdList = userListRVos.stream().map(UserListRVo -> UserListRVo.getPId()).collect(Collectors.toList());
            List<GetByPersonTagVo> personTags = personTagRelationService.getByPersonTag(userListVo.getComId(), pIdList);
            if (null != personTags) {
                Map<Long, List<GetByPersonTagVo>> listMap = personTags.stream().collect(Collectors.groupingBy(GetByPersonTagVo::getPId));
                for (UserListRVo userListRVo : userListRVos) {
                    userListRVo.setPTags(listMap.get(userListRVo.getPId()));
                }
            }
        }catch (Exception e) {
            e.printStackTrace();
            log.error(e.getMessage());
        }

        PageInfo<UserListRVo> userListRVoPageInfo = new PageInfo<>(userListRVos);
        return ResultUtil.success(userListRVoPageInfo);
    }

    //消费的用户信息
    @PostMapping(HumanServiceUrl.URL_getXfUserInfo)
    public Result<XfUserInfoVo> getXfUserInfo(Long comId, Long pId) {
        XfUserInfoVo xfUserInfoVo = personnelInfoService.getXfUserInfo(comId, pId);
        if (xfUserInfoVo == null) {
            return ResultUtil.error(ResultEnum.Err_4023);
        }
        if (CommonUtil.isNull(xfUserInfoVo.getPPhotoUrl2())) {
            xfUserInfoVo.setPPhotoUrl2(xfUserInfoVo.getPPhotoUrl());
        }
        return ResultUtil.success(xfUserInfoVo);
    }


    /**
     * 修改人员信息
     */
    @PostMapping(WxServiceUrl.URL_modifyPwd)
    public Result modifyPwd(@RequestBody PersonVo personVo) {
        Boolean b = personnelInfoService.modifyPwd(personVo.getComId(), personVo);
        if (!b) return ResultUtil.error(ResultEnum.Err_3014);
        return ResultUtil.success();
    }

    /**
     * 修改人员信息
     */
    @PostMapping(WxServiceUrl.URL_modifyPhoto)
    public Result modifyPhoto(@RequestBody PersonVo personVo) {
        Boolean b = personnelInfoService.modifyPhoto(personVo.getComId(), personVo);
        if (!b) return ResultUtil.error(ResultEnum.Err_3014);
        return ResultUtil.success();
    }


    /**
     * 检查学号和身份证是否有重复
     *
     * @param code
     * @param phone
     * @return
     */
    @PostMapping(HumanServiceUrl.URLP_checkUnique)
    public Result checkUnique(Long companyId, String code, String phone) {
        Integer num = personnelInfoService.checkUnique(companyId, code, phone);
        if (num == 0) {
            return ResultUtil.success();
        }
        return ResultUtil.error(ResultEnum.Err_2035);
    }

    /*2.2.21 根据姓名手机号获取人员信息 getPinfoByNamePhone
     * */
    @PostMapping(HumanServiceUrl.URL_PersonnelGetPinfoByNameAndCode)
    public Result getPinfoByNameCode(Long companyId, String name, String pCode) {

        return ResultUtil.success(personnelInfoService.getPinfoByNameAndCode(companyId, name, pCode));
    }



    /*
    2.2.26根据出生日获取人员与消费账户personnel/getPersonAccountByBorn
     * */
    @PostMapping(HumanServiceUrl.URL_getPersonAccountByBorn)
    public Result getPersonAccountByBorn(Long companyId,Integer accType , String pBorn) {
        return ResultUtil.success(personnelInfoService.getPersonAccountByBorn(companyId, accType, pBorn));
    }

    @PostMapping(HumanServiceUrl.URL_getPersonByPCodes)
    public Result getPersonByPCodes(@RequestBody GetPersonByPCodesRequest getPersonByPCodesRequest){
        return ResultUtil.success(personnelInfoService.getPersonByPCodes(getPersonByPCodesRequest.getComId(),getPersonByPCodesRequest.getPCodes()));
    }


    @PostMapping(HumanServiceUrl.URL_getPersonByIds)
    public Result<List<EntityPersonnelInfo>> getPersonByIds(@RequestBody GetPersonByPIdsRequest request){
        return ResultUtil.success(personnelInfoService.getPersonByIds(request.getComId(),request.getPIds()));
    }


    @PostMapping(HumanServiceUrl.URL_updateUserRegion)
    public Result updateUserRegion(@RequestBody UpdateUserRegionRequest request) {
        return ResultUtil.success(personnelInfoService.updateUserRegion(request.getComId(), request));
    }

    @PostMapping(HumanServiceUrl.URL_getStudentDateKq)
    public Result getStudentDateKq(@RequestBody StudentsDateOnlineRequest request) {
        return ResultUtil.success( mjKaoqinService.getRow(request.getComId(),request));
    }

    @PostMapping(HumanServiceUrl.URL_saveUserRegion)
    public Result saveUserRegion(Long comId) {
        mjKaoqinService.timerSave(comId);
        return ResultUtil.success();
    }


    @PostMapping(HumanServiceUrl.URL_studentsKqBydaysDetail)
    public Result studentsKqBydaysDetail(@RequestBody StudentsKqBydaysDetailRequest request) {
        return ResultUtil.success( mjKaoqinService.getHistoryList(request.getComId(),request));
    }

    //仅侨初用
    @PostMapping(HumanServiceUrl.URL_modifyUserState)
    public Result updateUserRegion() {
        mjKaoqinService.timerUpdate(110l);
        return ResultUtil.success();
    }

    //获取异常人脸人员
    @PostMapping(HumanServiceUrl.URL_getUserBypIds)
    public Result getUserBypIds(@RequestBody GetUserBypIdsReq request) {
        return ResultUtil.success(personnelInfoService.getUserListBypIds(request.getComId(),request.getPIds()));
    }



}


